import React, { PureComponent } from 'react';
import { Button, Message, Balloon } from '@teamix/ui';
import { YunxiaoIcon } from '@alife/devops-ui';
import exceed from 'utils/apimap';
import utils from 'utils';
import { getCachedRepoValue } from 'utils/repoIdCache';
import { isPre } from 'utils/tenant';
import { navigateOpen } from 'utils/router';
import docs from 'utils/docs';
import track from 'utils/track';
import './index.scss';
import intl from '../../../../../../../../../locale';

const { pathResource } = window.FORCE;
const cacheKey = getCachedRepoValue('repo_user');

export default class PipeGuide extends PureComponent {
  state = {
    hasPipelineGuide: false,
  };

  componentDidMount() {
    const hasCache = utils.getCachedData(`mr-pipeline-guide-${cacheKey}`);
    if (!hasCache) {
      this.getPipeLine();
    }
  }

  getPipeLine = () => {
    exceed
      .fetch({
        api: 'project.pipelines',
        params: {
          projectId: pathResource.id,
        },

        data: { per_page: 20, page: 1 },
      })
      .then((res) => {
        const total = res[0].amount;
        if (!total) {
          this.setState({
            hasPipelineGuide: true,
          });
        }
      });
  };

  onClose = () => {
    track({
      action: 'close_pipeline_guidance',
      page: 'mr-recommend',
      type: '',
      control: '',
    });

    this.setState({
      hasPipelineGuide: false,
    });

    utils.setCachedData(`mr-pipeline-guide-${cacheKey}`, true);
  };

  goToFlow = () => {
    const { resourceSubject } = window.FORCE;
    const { projectInfo } = this.props;
    track({
      action: 'create_pipeline',
      page: 'mr-recommend',
      type: '',
      control: '',
    });

    const tpl = {
      type: 'codeup',
      template: {
        id: pathResource.id,
        gitHttpURL: projectInfo.http_url_to_repo,
        branch: utils.revisionEncodeURI(resourceSubject.revision),
      },
    };

    const url = `https://${isPre ? 'pre-' : ''}flow.aliyun.com/my/new?sourceTpl=${btoa(
      JSON.stringify(tpl),
    )}`;
    navigateOpen(url);
  };

  render() {
    const { hasPipelineGuide } = this.state;
    const hasCache = utils.getCachedData(`mr-pipeline-guide-${cacheKey}`);
    if (hasCache) return null;
    return hasPipelineGuide ? (
      <div className="mr-pipeline-guide">
        <Message type="notice" closeable onClose={this.onClose}>
          <div className="mr-pipeline-guide-content">
            <div className="mr-pipeline-guide-content-text">
              <Balloon
                closable={false}
                // type="primary"
                // popupClassName="suggestion-tooltip"
                // popupStyle={{ background: '#f7f7f7' }}
                align="t"
                trigger={
                  <span className="suggestion">
                    {intl.get({
                      id: 'code-assets.components.pipeGuide.RecommendedOptimization',
                      defaultMessage: '推荐优化',
                    })}
                    <YunxiaoIcon type="question-line" />
                  </span>
                }
              >
                <a href={docs('howToUsePipelineDetection')} target="_blank" rel="noreferrer">
                  {intl.get({
                    id: 'code-assets.components.pipeGuide.HowToUsePipelineDetection.1',
                    defaultMessage: '如何使用流水线检测？',
                  })}
                </a>
              </Balloon>
              <div>
                <span className="pipeline-test">
                  {intl.get({
                    id: 'code-assets.components.pipeGuide.CustomExtendedPipelineDetection',
                    defaultMessage: '自定义扩展流水线检测',
                  })}
                </span>
                <span className="tips">
                  {intl.get({
                    id: 'code-assets.components.pipeGuide.EasilyCreate',
                    defaultMessage: '轻松创建',
                  })}
                </span>
                <span style={{ margin: '0 8px' }}>|</span>
                <span className="tips">
                  {intl.get({
                    id: 'code-assets.components.pipeGuide.AutomaticScaling',
                    defaultMessage: '自动扩展',
                  })}
                </span>
                <span style={{ margin: '0 8px' }}>|</span>
                <span className="tips">
                  {intl.get({
                    id: 'code-assets.components.pipeGuide.FlexibleDetection',
                    defaultMessage: '灵活检测',
                  })}
                </span>
              </div>
            </div>
            <div>
              <Button onClick={this.goToFlow}>
                {intl.get({
                  id: 'code-assets.components.pipeGuide.CreateNow',
                  defaultMessage: '立即创建',
                })}
              </Button>
            </div>
          </div>
        </Message>
        {/* <span className="mr-pipeline-guide-close" onClick={this.onClose}>x</span>
        <div className="mr-pipeline-guide-content">
         <div style={{ width: '42px', height: '42px' }}>img</div>
         <div className="mr-pipeline-guide-content-text">
           <span>一分钟轻松创建流水线</span>，自动执行单元测试及代码检测，提升代码合并质量<br />
           <a>如何在合并请求中使用流水线？</a>
         </div>
         <div><Button>立即创建</Button></div>
        </div> */}
      </div>
    ) : null;
  }
}
